require "ftools";

class Episode < ActiveRecord::Base
  belongs_to :podcast;
  has_one :post;
  has_many :participations;
  has_many :users, :through => :participations;
  has_many :taggings, :as => :taggable;
  has_many :tags, :through => :taggings;
  
  validates_presence_of :title, :file, :format, :podcast_id;
  validates_uniqueness_of :file;
  validate :must_have_user;
  
  EPISODES_DIR = (RAILS_ENV == "test") ? "public/test_episodes" : "public/episodes";
  
  def user?(user)
    users.include?(user);
  end
  
  def guest?(user)
    guests.include?(user);
  end

  def guests
    users.reject{|user| podcast.user?(user);};
  end

  def file=(original_file)
    Dir.inside(EPISODES_DIR) do;
      Dir.mkdir "#{podcast.id}" rescue nil;
    
      create = !original_file.kind_of?(File);
      original_file = File.new(original_file, "r") if create;
      File.open "#{podcast.id}/#{self.id}.#{extension}", "w" do |file|
        file.write(original_file.read);
      end
      self[:file] = "#{EPISODES_DIR}/#{podcast.id}/#{self.id}.#{extension}";
    
      original_file.close if create;
    end
  end

  def extension
    return {
      "audio/mpeg" => :mp3
    }[format];
  end
  
  protected
  def must_have_user
    errors.add_to_base("Episode must have at least one user") if users.empty?;
  end
  
end